<?php

namespace app\Modules\Api\controllers;

use Yii;
use app\Modules\Api\models\User;
use app\Modules\Api\models\Bill;
use app\filters\Json;
use app\helpers\Request;
use dosamigos\qrcode\QrCode;
use yii\helpers\Url;
use yii\data\Pagination;


/**
 * Class ExtendController
 * @package app\Modules\Api\controllers
 */
class ExtendController extends ControllerBase
{
    /**
     * 注册
     * @return array
     */
    public function actionIndex()
    {
        $user_id = Request::strictpost('user_id','缺少用户id');
        $thisuser = User::findOne($user_id);
        if(!$thisuser) {
            return Json::error('找不到此用户');
        }

        $sort = $thisuser->sort.','.$user_id;
        $query = User::find()->where("sort like '{$sort}%'");

        $count = $query->count();
        $pagination = new Pagination([
            'totalCount' => $count,
            'pageSize'=>Yii::$app->request->post('pageSize',6),
            'page'=>Yii::$app->request->post('page'),
        ]);
        $user_objects = $query->offset($pagination->offset)->limit($pagination->limit)->all();
        $users = [];
        $thislevel = $thisuser->getLevel();
        /**
         * @var  $key
         * @var  $object User
         */
        foreach($user_objects as $key=>$object)
        {
            $users[$key] = $object->toArray(['userid','name','take_money']);
            $level = $object->getLevel()-$thislevel;
            $users[$key]['name'] .= "({$level}级)";
        }
        $code_url = Yii::$app->params['baseUrlnotend'].Url::to(['qrcode','user_id'=>$user_id]);
        $data = [
            'take_money'=>strval($thisuser->take_money),
            'code_url'=>$code_url,
            'users'=>$users,
        ];
        return Json::success($data);
    }

    /**
     * @return array
     */
    public function actionView()
    {
        $user_id = Request::strictpost('user_id','缺少用户id');


        $user = User::findOne($user_id);
        if(!$user) {
            return Json::error('找不到此用户');
        }

        $query = Bill::find()->where(['user_id'=>$user_id]);
        $count = $query->count();
        $pagination = new Pagination([
            'totalCount' => $count,
            'pageSize'=>Yii::$app->request->post('pageSize',6),
            'page'=>Yii::$app->request->post('page'),
        ]);
        $bills = $query
            ->offset($pagination->offset)
            ->limit($pagination->limit)
            ->orderBy(['billid'=>SORT_DESC])
            ->all();
        return Json::success([
            'bills'=>$bills,
            'bill_count'=>$count,
        ]);
    }

    public function actionQrcode($user_id)
    {
        $this->html();
        QrCode::png(Yii::$app->params['baseUrlnotend'].'/site/contact?user_id='.$user_id);
    }
}